<?php
namespace App\Controller;
use Cake\Cache\Cache;

class ArticlesController extends AppController{

    public $displayNum = 30;
    public function initialize()
    {
        parent::initialize();
    }

    /*
     * create by phpstorm
     * author：Ming
     * date：2020.04.13
     * ps：清除缓存
     * */
    public function deleteRedis($type = null)
    {
        if($type == 'all'){
            Cache::clearAll(false);
        }else{
            $pass = $this->request->getData('pass');
//            if($pass != md5('123456789.')){
//                $this->G->error("pass_error");
//                return null;
//            }
            $key = $this->request->getData('key');
            $time = $this->request->getData('time');
            Cache::delete($key,$time);
        }
        $this->G->success("success");
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.21
   * ps：获取文章信息
   * */
    public function getInfo()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $id  = $this->request->getData('id');
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        $this->loadComponent('ArticleCache');
        $article = $this->ArticleCache->getVal($id);
        $article['add_time'] = date('Y-m-d H:i:s', $article['add_time']);
        $this->loadComponent('ViewCache');
        $views = $this->ViewCache->getVal('articles', $id);
        $this->loadComponent('TextareaCache');
        $content = $this->TextareaCache->getVal('articles', $id);
        $this->loadComponent('ContentFormat');
        $article['content']  = empty($content) ? '' : $this->ContentFormat->add($content['content']);
        $article['view'] = empty($views) ? 0 : $views['v'];
        $article['pre_view'] = empty($views) ? 0 : $views['p'];
        $article['img'] = empty($article['img']) ? '' : $this->G->getImgUrl($article['img']);
        $this->loadComponent('CategoryContentCache');
        $article['category_id'] = $this->CategoryContentCache->getCategories('articles', $id)[0];
        $this->loadModel('Categories');
        $category_name = $this->Categories->findById($article['category_id'])->select(['alias'])->first();
        $article['category_name'] = $category_name['alias'];
        $this->G->success('Success', $article);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.21
   * ps：获取文章分类
   * */
    public function getCategories()
    {
        $this->loadComponent('SysconfigCache');
        $cid = $this->SysconfigCache->getVal('article_category');
        $this->loadModel('Categories');
        $data = $this->Categories->find('children',['for'=>$cid])
            ->find('treeList',['keyPath'=>'id','valuePath'=>'alias'])
            ->toArray();
        $this->G->success('Success', $data);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.08
   * ps：获取文章列表
   * */
    public function getList()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $title  = $this->request->getData('title');
        $category_id  = $this->request->getData('category_id');
        $enabled  = $this->request->getData('enabled');
        $page = $this->request->getData('page');
        $page = empty($page) ? 1 : $page;
        $where = [];
        $where['is_delete'] = 0;
        if(!empty($title)){
            $where['title like '] = '%'.$title.'%';
        }
        if(is_numeric($enabled)){
            $where['enabled'] = $enabled;
        }
        $this->loadModel('CategoryContents');
        if(!empty($category_id)){
            $category_contents = $this->CategoryContents->find()
                ->select(['content_id'])
                ->where(['content_type'=>'articles','category_id'=>$category_id])
                ->toArray();
            if(!empty($category_contents)){
                $where['id in'] = array_column($category_contents, 'content_id');
            }
        }
        $articles = $this->Articles->find()
            ->where($where)
            ->order(['id desc'])
            ->limit($this->displayNum)
            ->page($page);
        $re = [];
        $count = $articles->count();
        $re['pageTotal'] = ceil($count/$this->displayNum);
        $articles = $articles->toArray();
        $re['list'] = [];
        if(!empty($articles)){
            $this->loadComponent('CategoryContentCache');
            $this->loadModel('Categories');
            foreach ($articles as $k=>$v){
                $category_id = $this->CategoryContentCache->getCategories('articles', $v['id'])[0];
                $category_name = $this->Categories->findById($category_id)->select(['alias'])->first();
                $re['list'][] = [
                    'id'=>$v['id'],
                    'title'=>$v['title'],
                    'category_name'=>$category_name['alias'],
                    'enabled'=>$v['enabled'],
                    'display'=>$v['display'],
                    'order_num'=>$v['order_num'],
                ];
            }
        }
        $this->G->success('Success', $re);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.08
   * ps：修改文章
   * */
    public function update()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $id  = $this->request->getData("id");
        $title = $this->request->getData("title");
        $content = $this->request->getData("content");
        $pre_view = $this->request->getData("pre_view");
        $category_id = $this->request->getData("category_id");
        $enabled = $this->request->getData("enabled");
        $display = $this->request->getData("display");
        $is_hot = $this->request->getData("is_hot");
        $img = $this->request->getData("img");
        $order_num = $this->request->getData("order_num");
        $pre_view = empty($pre_view) ? 0 : $pre_view;
        $order_num = empty($order_num) ? 0 : $order_num;
        $is_hot = empty($is_hot) ? 0 : $is_hot;
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        if(empty($title)){
            $this->G->error("title_error");
            return null;
        }
        if(empty($content)){
            $this->G->error("content_error");
            return null;
        }
        if(empty($img)){
            $this->G->error("img_error");
            return null;
        }
        $this->loadComponent('ArticleCache');
        $data = $this->ArticleCache->getVal($id);
        if(empty($data)){
            $this->G->error("article_not_found");
            return null;
        }
        $article = $this->Articles->newEntity();
        $article->id = $id;
        $article->title = $title;
        $article->enabled = $enabled;
        $article->display = $display;
        $article->is_hot = $is_hot;
        $article->img = $this->G->setImgUrl($img);
        $article->order_num = $order_num;
        $article_save = $this->Articles->save($article);
        if(!$article_save){
            $this->G->error("save_error");
            return null;
        }
        if(!empty($category_id)){
            $this->loadModel('CategoryContents');
            $category_contents = $this->CategoryContents->find()
                ->select(['id','category_id'])
                ->where(['content_type'=>'articles','content_id'=>$id])
                ->first();
            if($category_contents['category_id'] != $category_id){
                $this->loadComponent('CategoryContentCache');
                $this->CategoryContentCache->add('articles', $id, $category_id);
                $this->CategoryContents->deleteAll(['id'=>$category_contents['id']]);
            }
        }
        $this->loadComponent('TextareaCache');
        $this->loadComponent('ContentFormat');
        $content  = $this->ContentFormat->clean($content)[0];
        $this->TextareaCache->update('articles', $id, $content);
        $this->ArticleCache->deleteCache($id);
        $this->ArticleCache->deleteList();
        $this->loadComponent('ViewCache');
        $this->ViewCache->updateCache('article', $id, ['p'=>$pre_view]);
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.07
   * ps：新增文章
   * */
    public function add()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $title = $this->request->getData("title");
        $content = $this->request->getData("content");
        $category_id = $this->request->getData("category_id");
        $pre_view = $this->request->getData("pre_view");
        $enabled = $this->request->getData("enabled");
        $display = $this->request->getData("display");
        $is_hot = $this->request->getData("is_hot");
        $img = $this->request->getData("img");
        $order_num = $this->request->getData("order_num");
        $pre_view = empty($pre_view) ? 0 : $pre_view;
        $order_num = empty($order_num) ? 0 : $order_num;
        $is_hot = empty($is_hot) ? 0 : $is_hot;
        if(empty($title)){
            $this->G->error("title_error");
            return null;
        }
        if(empty($content)){
            $this->G->error("content_error");
            return null;
        }
        if(empty($img)){
            $this->G->error("img_error");
            return null;
        }
        $user_id = $this->Jwt->get('user_id');
        $time = time();
        $article = $this->Articles->newEntity();
        $article->title = $title;
        $article->user_id = $user_id;
        $article->add_time = $time;
        $article->enabled = $enabled;
        $article->is_hot = $is_hot;
        $article->img = $this->G->setImgUrl($img);
        $article->display = $display;
        $article->order_num = $order_num;
        $article_save = $this->Articles->save($article);
        if(!$article_save){
            $this->G->error("save_error");
            return null;
        }
        if(!empty($category_id)){
            $this->loadComponent('CategoryContentCache');
            $this->CategoryContentCache->add('articles', $article_save->id, $category_id);
        }
        $this->loadComponent('ArticleCache');
        $this->loadComponent('TextareaCache');
        $this->loadComponent('ContentFormat');
        $this->loadComponent('ViewCache');
        $this->ViewCache->updateCache('article', $article_save->id, ['p'=>$pre_view]);
        $content  = $this->ContentFormat->clean($content)[0];
        $this->TextareaCache->add('articles', $article_save->id, $content);
        $this->ArticleCache->createCache($article_save->id);
        $this->ArticleCache->deleteList();
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.07
   * ps：删除文章
   * */
    public function delete()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $id = $this->request->getData("id");
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        $this->loadComponent('ArticleCache');
        $this->loadComponent('CategoryContentCache');
        $cache = $this->ArticleCache->getVal($id);
        if(empty($cache)){
            $this->G->error("not_found");
            return null;
        }
        $this->Articles->query()
            ->update()
            ->set(['is_delete'=>1])
            ->where(['id' => $id])
            ->execute();
//        $this->Articles->deleteAll(['id'=>$id]);
        $this->ArticleCache->deleteCache($id);
        $this->ArticleCache->deleteList();
        $this->loadComponent('TextareaCache');
        $this->TextareaCache->delete('articles', $id);
//        $ids = $this->CategoryContentCache->getCategories('articles', $id);
//        if(!empty($ids)){
//            foreach ($ids as $k=>$v){
//                $this->ArticleCache->deleteList($v);
//            }
//        }
        $this->G->success('Success');
    }
}
?>